#coding=utf-8
#get realtime price from shou

import stutils,datetime
from decimal import *

def get_soup(code):
    url = 'http://stock.business.sohu.com/q/bc.php?code=%s'%code
    return stutils.get_soup(url)

def get_data(soup):

    def is_exday(soup):
    
        cjl = soup.find( text=unicode('成交量', 'u8') )
        raw_volume = cjl.parent.nextSibling.string
        volume = int(''.join(raw_volume.split(';')[-1].split(',')))*100
    
        if volume == 0 :return False
        return True
    
    r = is_exday(soup)
    if not r: return None

    #date,time,current_price,zd,volume,amount,high,low,open
    data = []

    sj = unicode('手机查询行情', 'u8')
    sj = soup.find(text=sj)
    td = sj.parent.parent.parent.nextSibling
    cs = td.contents
    
    dt = cs[0].string.split('&')[0]
    data.append( dt.split(' ')[0])
    data.append( dt.split(' ')[1])
    #current_price
    p = cs[1].b.string
    data.append( p )
    #涨跌
    raw_zd = cs[2].find(text= lambda(x): x.find('%')!=-1)
    data.append(raw_zd.split(';')[-1][:-1])
    
    
    table2 = soup.find(text=unicode('成交量', 'u8') ).parent.parent.parent
    cs2 = table2.contents
    
    raw_volume = cs2[1].find(text= lambda(x): x.find(';')!=-1)
    data.append(int(''.join(raw_volume.split(';')[-1].split(',')))*100)
    
    raw_amount = cs2[3].find(text= lambda(x): x.find(unicode('元', 'u8'))!=-1)
    data.append( int(''.join(raw_amount.split(' ')[0].split(','))) * 10000 ) 
    
    raw_interval = cs2[5].find(text= lambda(x): x.find(';')!=-1).split(';')[-1]
    low = raw_interval.split('-')[0]
    high = raw_interval.split('-')[1].strip()
    data.append(high)
    data.append(low)
    
    raw_open = cs2[7].find(text= lambda(x): x.find(';')!=-1)
    data.append(raw_open.split(';')[-1])
    
    #买卖5档
    wb = unicode('委&nbsp;&nbsp;比', 'u8')
    wbtr = soup.find(text=wb).parent.parent
    table3 = soup.find(text=wb).parent.parent.parent
    trs = table3.findAll('tr')
    
    i = 0
    for tr in trs:
        if tr == wbtr:
            i = trs.index(wbtr) + 1    
            break
            
    trs = trs[i:]    
    mmtrs = trs[0:5] + trs[6:11]
    
    mm5d = []
    for i in mmtrs:
        rawdata = i.contents[1].font.string
        l = rawdata.split('&nbsp;')
        p = l[1]
        v = str( int(l[3])*100 )
        mm5d.append([p, v])
        
    data = [str(d) for d in data]
    return data,mm5d

class NoLivePriceNowError(Exception):
    def __init__(self, code):
        self.code = code
    def __str__(self):
        return "%s: No Live Price Now."%self.code
    
def get_rtprice(code):
    '''数据格式:
        1 [ date, time, 当前价格, 涨跌, 成交量, 成交金额, high, low, 开盘价 ];
        2 买卖五档;
    '''
    s = get_soup(code)
    data = get_data(s)
    if not data:
        raise NoLivePriceNowError(code)
    return data

if __name__ == '__main__':
    data = get_rtprice('600332')
    print data